
# JSON 数据解析(JavaScript Object Notation)
'''
Python 编码为 JSON 类型转换对应：
dict	    object
list,tuple	array
str	        string
int, float  number
True	    true
False	    false
None	    null
'''
'''
JSON 解码为 Python 类型转换对应表：
object	        dict
array	        list
string	        str
number(int)     int
number(real)    float
true	        True
false	        False
null	        None
'''
import json
# 字符串处理用 json.dumps() 和 json.loads()
# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Baidu',
    'url' : 'http://www.baidu.com'
}
json_str = json.dumps(data1)
print ("Python dict:", repr(data1))
print ("JSON object:", json_str)
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
print()

# 文件处理用 json.dump() 和 json.load()
# 写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data1, f)
# 读取数据 文件编码格式为ANSI时才能正常读取
with open('school.json', 'r') as f:
    data = json.load(f)
# print(data[0]['school'][0]['name'])
while True:
    try:
        idStr = input("School ID:")
        if len(idStr) == 0:
            break
        idInt = int(idStr)
        calPara = 10**(len(idStr) - 1)
        idF = (idInt//calPara) - 1
        idS = (idInt % calPara) - 1
        # print(idF, idS)
        if idF < 0 or idS < 0:
            print(idStr + " is not a valid id!")
        else:
            print(data[idF]['school'][idS]['name'])
    except Exception as exp:
        print(idStr + " is not a valid id!")
        # print(exp)
